﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Read.Api.Application.Command.User;
using Provenance.Read.Api.Dto.User;

namespace Provenance.Read.Api.Application.CommandHandler.User
{
    public class GetUserListCommandHandler : IRequestHandler<GetUserListCommand, ApiResult<PagingResult<IList<GetUserListResponseDTO>>>>
    {
        private readonly IUserInfoRepository _userInfoRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IRoleRepository _roleRepository;
        private readonly ILogger<GetUserListCommandHandler> _logger;
        private readonly IMapper _mapper;
        public GetUserListCommandHandler(IUserInfoRepository userInfoRepository, IUserRoleRepository userRoleRepository, ILogger<GetUserListCommandHandler> logger, IMapper mapper, IRoleRepository roleRepository)
        {
            _userInfoRepository = userInfoRepository;
            _userRoleRepository = userRoleRepository;
            _logger = logger;
            _mapper = mapper;
            _roleRepository = roleRepository;
        }
        public async Task<ApiResult<PagingResult<IList<GetUserListResponseDTO>>>> Handle(GetUserListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var userList = await _userInfoRepository.GetAllAsync(x => !x.IsDeleted);
                var result = _mapper.Map<IList<GetUserListResponseDTO>>(userList);
                foreach (var user in result)
                {
                    var userRoleList = await _userRoleRepository.GetAllAsync(x => x.UserId == user.UserId&&!x.IsDeleted);
                    int[] roleIds = userRoleList.Select(x => x.RoleId).ToArray();
                    var rolelist = await _roleRepository.GetAllAsync(x => roleIds.Contains(x.RoleId)&&!x.IsDeleted);
                    string[] roleNames = rolelist.Select(x => x.RoleName).ToArray();
                    //显示每一个用户的所有角色名称
                    user.RoleNames = string.Join(",", roleNames);
                }
                var responseList = result.OrderBy(x => x.UserId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                var pagingResult = new PagingResult<IList<GetUserListResponseDTO>>()
                {
                    TotalCount = result.Count(),
                    TotalPage = (int)Math.Ceiling(result.Count() * 1.0 / request.PageSize),
                    Data = responseList
                };
                return ApiResult<PagingResult<IList<GetUserListResponseDTO>>>.Success(pagingResult);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in {nameof(GetUserListCommandHandler)}" + ex.Message);
                return ApiResult<PagingResult<IList<GetUserListResponseDTO>>>.Failure(ex.Message);
            }
        }
    }
}
